from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import os

class TTSRequestHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        self.end_headers()

    def do_POST(self):
        if self.path == '/api/tts/convert':
            content_length = int(self.headers.get('Content-Length', 0))
            auth_header = self.headers.get('Authorization')

            if not auth_header or not auth_header.startswith('Bearer '):
                self.send_error(401, 'Unauthorized')
                return

            try:
                post_data = self.rfile.read(content_length)
                request_data = json.loads(post_data.decode('utf-8'))
                text = request_data.get('text')
                lang_type = request_data.get('langType')

                # 这里应该是实际的TTS转换逻辑
                # 目前返回一个示例MP3文件
                sample_mp3_path = os.path.join(os.path.dirname(__file__), 'word-audio', 'can.mp3')
                
                if os.path.exists(sample_mp3_path):
                    with open(sample_mp3_path, 'rb') as f:
                        audio_data = f.read()
                else:
                    self.send_error(500, 'Sample audio file not found')
                    return

                self.send_response(200)
                self.send_header('Content-Type', 'audio/mp3')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Content-Length', str(len(audio_data)))
                self.end_headers()
                self.wfile.write(audio_data)

            except Exception as e:
                self.send_error(500, str(e))
        else:
            self.send_error(404)

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, TTSRequestHandler)
    print('Starting server on port 8000...')
    httpd.serve_forever()